package com.dmyang.common.intercepter;

import com.dmyang.entity.HyUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Session登录拦截器
 * Created by brss on 2017/8/8.
 */
public class SessionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();
        System.out.println(uri);
        //放过登录页面
        if ( uri.toLowerCase().indexOf("login")>=0  ){
            return true;
        }
        //其他所有的页面，只有包含admin的，都拦截，并判断是否登录
        if( uri.toLowerCase().contains("admin")){
            HttpSession session = request.getSession();
            HyUser user = (HyUser)session.getAttribute("userinfo");
            if(user!=null){
                return true;
            }
            request.getRequestDispatcher("/login").forward(request,response);
            return false;
        }
        //漏洞：没有拦截Category，Article，Tag等管理uri。因为前台有可能用到。
        if(
                uri.toLowerCase().contains("category/add") ||   //拦截分类操作
                uri.toLowerCase().contains("category/modify") ||
                uri.toLowerCase().contains("category/delete") ||
                uri.toLowerCase().contains("article/add") ||    //拦截文章操作
                uri.toLowerCase().contains("article/addDraft") ||
                uri.toLowerCase().contains("article/delete") ||
                uri.toLowerCase().contains("article/modify") ||
                uri.toLowerCase().contains("article/modifyDraft")
                ){
            HttpSession session = request.getSession();
            HyUser user = (HyUser)session.getAttribute("userinfo");
            if(user!=null){
                return true;
            }
            request.getRequestDispatcher("/login").forward(request,response);
            return false;
        }
        //其他的页面（这里指的是前台页面，放过）
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
